package com.cqrt.aop;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqrt.mapper.RTTaskMapper;
import com.hustcad.plm.rpm.model.dto.active.TyppmActiveTreeDTO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Aspect
@Component
@Slf4j
@Transactional
public class PlanActivityAop {
    @Resource
    private RTTaskMapper rtTaskMapper;
    @Around("execution(* com.hustcad.plm.rpm.service.plan.TyppmPlanActiveService.queryPlanActiveTreeByRootOIDAndRootOTYPE(..))")
    public Object insertPlanActive(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            Object result = joinPoint.proceed();
            // 处理JSONObject类型：直接写入ibaAttribute
            if (result instanceof com.alibaba.fastjson.JSONObject) {
                com.alibaba.fastjson.JSONObject jsonResult = (com.alibaba.fastjson.JSONObject) result;
                JSONArray tasks = jsonResult.getJSONArray("Tasks");
                for (int i = 0; i < tasks.size(); i++){
                    JSONObject jsonObject = tasks.getJSONObject(i);
                    callBack(jsonObject);
                }
            }
            // 如果返回结果是TyppmActiveTreeDTO列表，则处理IBA属性
            else if (result instanceof List) {
                @SuppressWarnings("unchecked")
                List<TyppmActiveTreeDTO> treeDTOList = (List<TyppmActiveTreeDTO>) result;
            }
            return result;
        } catch (Exception e) {
            log.error("处理计划活动树IBA属性时发生异常", e);
            throw e;
        }
    }

    public void callBack(JSONObject jsonObject){
        JSONObject j1 = jsonObject.getJSONObject("ibaAttribute");
        if (j1==null){
            j1 = new JSONObject();
        }
        //处理时间显示问题（项目管理281）
        String s = jsonObject.getString("Start");
        String f = jsonObject.getString("Finish");
        if (StrUtil.isNotBlank(s)){
            int i = s.indexOf(".");
            if (i>0){
                jsonObject.put("Start", s.substring(0,i));
            }
        }
        if (StrUtil.isNotBlank(f)){
            int i = f.indexOf(".");
            if (i>0){
                jsonObject.put("Finish", f.substring(0,i));
            }
        }

        if (jsonObject.containsKey("ActualFinish")){

            if (jsonObject.containsKey("UID")){
                String jobOid = jsonObject.getString("UID");
                LocalDateTime actualFinshTime = rtTaskMapper.selectActualFinshTime(jobOid);
                if (actualFinshTime!=null){
                    jsonObject.put("ActualFinish",actualFinshTime);
                }
            }

            j1.put("ActualFinish",Collections.singletonList(jsonObject.getString("ActualFinish")));
        }
        if (jsonObject.containsKey("ActualStart")){
            Object start =  jsonObject.get("Start");
            if (StrUtil.isNotBlank(jsonObject.getString("executedStatusDisplayName"))&&!"未发布".equals(jsonObject.getString("executedStatusDisplayName"))){
                String jobOid = jsonObject.getString("UID");
                LocalDateTime actualStartTime = rtTaskMapper.selectActualStartTime(jobOid);
                if (actualStartTime!=null){
                    jsonObject.put("ActualStart",actualStartTime);
                }else {
                    rtTaskMapper.updateActualStartTime(jobOid);
                }
                j1.put("ActualStart",Collections.singletonList(jsonObject.getString("ActualStart")));
            }
        }


        if (StrUtil.isBlank(jsonObject.getString("ActualFinish"))||StrUtil.isBlank(jsonObject.getString("Start"))){
            j1.put("ActualDuration", Collections.singletonList(0L));
        }else {
            LocalDateTime actualFinish = LocalDateTime.parse(jsonObject.getString("ActualFinish"));
            LocalDateTime actualStart = LocalDateTime.parse(jsonObject.getString("Start"));
            long l = calculateWorkdaysBetween(actualStart, actualFinish);
            j1.put("ActualDuration",Collections.singletonList(l));
        }
        JSONArray jsonArray = jsonObject.getJSONArray("children");
        if (CollUtil.isEmpty(jsonArray)){
            return;
        }
        for(int i=0;i<jsonArray.size();i++){
            callBack(jsonArray.getJSONObject(i));
        }
    }

    public static long calculateWorkdaysBetween(LocalDateTime start, LocalDateTime end) {
        if (null == start || null == end) {
            return 0;
        }
        if (start.isAfter(end)) {
            LocalDateTime temp = start;
            start = end;
            end = temp;
        }
        long workingDays = 0;
        LocalDate currentDate = start.toLocalDate();
        LocalDate endDate = end.toLocalDate();
        while (!currentDate.isAfter(endDate)) {
            DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
            if (dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY) {
                workingDays++;
            }
            currentDate = currentDate.plusDays(1);
        }
        return workingDays;
    }
}